package com.heima.wemedia.service.impl;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.apis.article.IArticleClient;
import com.heima.common.constants.WemediaConstants;
import com.heima.common.constants.WmNewsMessageConstants;
import com.heima.common.exception.CustomException;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.NewsAuthDto;
import com.heima.model.wemedia.dtos.WmNewsDto;
import com.heima.model.wemedia.dtos.WmNewsPageReqDto;
import com.heima.model.wemedia.pojos.*;
import com.heima.utils.thread.WmThreadLocalUtil;
import com.heima.wemedia.mapper.*;
import com.heima.wemedia.service.WmNewsAutoScanService;
import com.heima.wemedia.service.WmNewsService;
import com.heima.wemedia.service.WmNewsTaskService;
import com.heima.wemedia.service.WmUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
@Transactional
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {
    /**
     * 条件查询文章列表
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findList(WmNewsPageReqDto dto) {
        //1.检查参数
        //分页检查
        dto.checkParam();
        //2.分页查询
        IPage page = new Page(dto.getPage(), dto.getSize());
        LambdaQueryWrapper<WmNews> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        //根据状态精确查询
        lambdaQueryWrapper.eq(dto.getStatus() != null, WmNews::getStatus, dto.getStatus());
        //频道精确查询
        lambdaQueryWrapper.eq(dto.getChannelId() != null, WmNews::getChannelId, dto.getChannelId());
        //时间范围查询
        if (dto.getBeginPubDate() != null && dto.getEndPubDate() != null) {
            lambdaQueryWrapper.between(WmNews::getPublishTime, dto.getBeginPubDate(), dto.getEndPubDate());
        }
        //关键字模糊查询
        if (StringUtils.isNotBlank(dto.getKeyword())) {
            lambdaQueryWrapper.like(WmNews::getTitle, dto.getKeyword());
        }
        //查询当前登录人的文章（线程获取id）
        lambdaQueryWrapper.eq(WmNews::getUserId, WmThreadLocalUtil.getUser().getId());
        //按照发布时间倒序查询
        lambdaQueryWrapper.orderByDesc(WmNews::getPublishTime);
        page = page(page, lambdaQueryWrapper);
        //3.结果返回
        ResponseResult responseResult = new PageResponseResult(dto.getPage(), dto.getSize(), (int) page.getTotal());
        responseResult.setData(page.getRecords());   //将数据设置到返回数据中
        return responseResult;
    }

    @Autowired
    private WmNewsMaterialMapper mapper;
    @Autowired
    private WmMaterialMapper materialMapper;
    @Autowired
    private WmNewsAutoScanService wmNewsAutoScanService;
    @Autowired
    private WmNewsTaskService wmNewsTaskService;

    /**
     * 发布修改文章或保存草稿
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult submitNews(WmNewsDto dto) {
        //0.条件判断
        if (dto == null || dto.getContent() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //1.保存或修改文章
        WmNews wmNews = new WmNews();
        //属性拷贝  属性名和类型相同时才能拷贝
        BeanUtils.copyProperties(dto, wmNews);
        //封面图片 list->string
        if (dto.getImages() != null && dto.getImages().size() > 0) {
            String imageStr = StringUtils.join(dto.getImages(), ",");
            wmNews.setImages(imageStr);
        }
        //如果当前封面类型为-1
        if (dto.getType().equals(WemediaConstants.WM_NEWS_TYPE_AUTO)) {
            wmNews.setType(null);
        }
        saveOrUpdateWmNews(wmNews);
        //2.判断是否为草稿，如果为草稿结束当前方法
        if (dto.getStatus().equals(WmNews.Status.NORMAL.getCode())) {
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }
        //3.不是草稿
        //获取文章内容的图片信息
        List<String> materials = ectractUrlInfo(dto.getContent());
        //保存文章内容图片与素材的关系
        saveRelativeInfoForContent(materials, wmNews.getId());

        //4.不是草稿 ，保存文章封面图片与素材的关系
        saveRelativeInfoForCover(dto, wmNews, materials);

        //自动审核文章
        //wmNewsAutoScanService.autoScanWmNews(wmNews.getId());
        wmNewsTaskService.addNewsToTask(wmNews.getId(), wmNews.getPublishTime());

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Autowired
    private KafkaTemplate<String, String> kafkaTemplate;

    /**
     * 文章的上下架
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult downOrUp(WmNewsDto dto) {
        //1.检查参数
        if (dto.getId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.查询文章
        WmNews wmNews = getById(dto.getId());
        if (wmNews == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "文章不存在");
        }
        //3.判断文章是否已发布
        if (!wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "当前文章不是发布状态，不能上下架");
        }
        //4.修改文章 --字段 enable
        if (dto.getEnable() != null && dto.getEnable() > -1 && dto.getEnable() < 2) {
            LambdaUpdateWrapper<WmNews> wrapper = new LambdaUpdateWrapper<>();
            wrapper.set(WmNews::getEnable, dto.getEnable())
                    .eq(WmNews::getId, dto.getId());
            update(wrapper);
            if (wmNews.getArticleId() != null) {
                //发送消息通知article修改文章的配置
                Map<String, Object> map = new HashMap<>();
                map.put("articleId", wmNews.getArticleId());
                map.put("enable", dto.getEnable());
                kafkaTemplate.send(WmNewsMessageConstants.WM_NEWS_UP_OR_DOWN_TOPIC, JSON.toJSONString(map));
            }
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 查看文章详情
     * @param id
     * @return
     */
    @Override
    public ResponseResult oneById(Integer id) {
        //1.检查参数
        if (id==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.根据id查询文章信息
        WmNews wmNews = getById(id);
        if (wmNews==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"文章不存在");
        }
        //3.返回结果
        return ResponseResult.okResult(wmNews);
    }
    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;
    /**
     * 根据id删除文章
     * @param id
     * @return
     */
    @Override
    public ResponseResult delNews(Integer id) {
        //1.检查参数
        if (id==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"文章id不可缺少");
        }
        //2.判断文章是否存在
        LambdaQueryWrapper<WmNews> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(WmNews::getId,id);
        WmNews wmNews = getOne(queryWrapper);
        if (wmNews==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"文章不存在");
        }
        //3.检查文章是否已经上架
        if (wmNews.getEnable()==1){
            return ResponseResult.errorResult(501,"文章已发布，不能删除");
        }
        //4.未上架，先删除该新闻和该素材的关系表
        LambdaQueryWrapper<WmNewsMaterial> queryWrapper1=new LambdaQueryWrapper<>();
        queryWrapper1.eq(WmNewsMaterial::getNewsId,id);
        List<WmNewsMaterial> wmNewsMaterials = wmNewsMaterialMapper.selectList(queryWrapper1);
        if(wmNewsMaterials!=null&&wmNewsMaterials.size()!=0){
            //wmNewsMaterialMapper.deleteBatchIds(wmNewsMaterials);
            wmNewsMaterialMapper.delete(queryWrapper1);
        }
        //5.再删除文章数据
        removeById(id);
        //6.返回结果
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
    @Autowired
    private WmUserMapper wmUserMapper;

    /**
     * 查询人工审核文章列表
     * @param dto
     * @return
     */
    @Override
    public ResponseResult listVo(NewsAuthDto dto) {
        //1.检查参数
        dto.checkParam();
        //分页查询
        IPage<WmNews> page=new Page(dto.getPage(), dto.getSize());
        LambdaQueryWrapper<WmNews> queryWrapper=new LambdaQueryWrapper<>();
        //根据关键词模糊查询
        if (dto.getTitle()!=null&&StringUtils.isNotBlank(dto.getTitle())){
            queryWrapper.like(WmNews::getTitle,dto.getTitle());
        }
        //根据审核状态查询
        if (dto.getStatus()!=null){
            queryWrapper.eq(WmNews::getStatus,dto.getStatus());
        }
        //根据创建时间倒序排列数据
        queryWrapper.orderByDesc(WmNews::getCreatedTime);
        List<WmNews> list = list(queryWrapper);
        for (WmNews wmNews : list) {
            //通过uer_id查询作者姓名并装入其中
            Integer userId = wmNews.getUserId();
            WmUser wmUser = wmUserMapper.selectById(userId);
            wmNews.setAuthorName(wmUser.getName());
        }

        //分页查询
        int start = (int)((page.getCurrent() - 1) * page.getSize());
        int end = (int)((start + page.getSize()) > list.size() ? list.size() : (page.getSize() * page.getCurrent()));
        page.setTotal(list.size());
        if (page.getSize()*(page.getCurrent()-1) <= page.getTotal()) {
            // 分隔列表 当前页存在数据时 设置
            page.setRecords(list.subList(start, end));
        }

        //返回结果
        ResponseResult responseResult=new PageResponseResult(dto.getPage(),dto.getSize(), (int) page.getTotal());
        responseResult.setData(page.getRecords());
        return responseResult;
    }

    /**
     * 查询文章详情
     * @param id
     * @return
     */
    public ResponseResult oneVo(Integer id){
        //检查参数
        if(id==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //通过id查询该文章信息
        WmNews wmNews = getById(id);
        //将作者名称加入
        Integer userId = wmNews.getUserId();
        WmUser wmUser = wmUserMapper.selectById(userId);
        wmNews.setAuthorName(wmUser.getName());
        //返回结果
        return ResponseResult.okResult(wmNews);
    }

    /**
     * 人工审核失败
     * @param dto
     * @return
     */
    public ResponseResult authFail(NewsAuthDto dto){
        //1.检查参数
        if (dto.getId()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.添加驳回理由
        WmNews wmNews = getById(dto.getId());
        if(dto.getMsg()!=null&&StringUtils.isNotBlank(dto.getMsg())){
            wmNews.setReason(dto.getMsg());
        }
        //3.设置审核状态
        wmNews.setStatus((short) 2);
        updateById(wmNews);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
    @Autowired
    private IArticleClient articleClient;
    @Autowired
    private WmChannelMapper wmChannelMapper;

    /**
     * 人工审核成功
     * @param dto
     * @return
     */
    public ResponseResult authPass( NewsAuthDto dto){
        //1.检查参数
        if (dto.getStatus()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.修改文章审核状态
        WmNews wmNews = getById(dto.getId());
        wmNews.setStatus(dto.getStatus().shortValue());
        wmNews.setReason("审核成功");
        //3.创建app端文章信息---feign远程调用
        ResponseResult responseResult = saveAppArticle(wmNews);
        if (!responseResult.getCode().equals(200)){
            throw new RuntimeException("WmNewsServiceImpl--人工文章审核，保存app端相关文章数据失败");
        }
        //回填articleId
        wmNews.setArticleId((Long) responseResult.getData());
        updateById(wmNews);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);

    }

    /**
     * 保存app端的相关文章数据
     * @param wmNews
     */
    private ResponseResult saveAppArticle(WmNews wmNews) {
        ArticleDto dto=new ArticleDto();
        //属性拷贝
        BeanUtils.copyProperties(wmNews,dto);
        //设置文章布局
        dto.setLayout(wmNews.getType());
        //设置频道
        WmChannel wmChannel = wmChannelMapper.selectById(wmNews.getChannelId());
        if (wmChannel!=null){
            dto.setChannelName(wmChannel.getName());
        }
        //设置作者id和姓名
        dto.setAuthorId(wmNews.getUserId().longValue());
        WmUser wmUser = wmUserMapper.selectById(wmNews.getUserId());
        if (wmUser!=null){
            dto.setAuthorName(wmUser.getName());
        }
        //必须设置文章的id否则会新建
        if (wmNews.getArticleId()!=null){
            dto.setId(wmNews.getArticleId());
        }
        //创建时间
        dto.setCreatedTime(new Date());
        ResponseResult responseResult = articleClient.saveArticle(dto);
        return responseResult;
    }

    /**
     * 功能1.如果当前封面类型为自动，则设置封面类型
     * 匹配规则：
     * 1.如果内容图片大于等于1，小于3 单图    type1
     * 2.如果内容图片大于等于3 多图    type3
     * 3.如果内容没有图片，无图   type0
     * 功能2.保存封面图片与素材的关系
     *
     * @param dto
     * @param wmNews
     * @param materials
     */
    private void saveRelativeInfoForCover(WmNewsDto dto, WmNews wmNews, List<String> materials) {
        List<String> images = dto.getImages();
        //1.如果当前封面类型为自动，则设置封面类型
        if (dto.getType().equals(WemediaConstants.WM_NEWS_TYPE_AUTO)) {
            //判断为多图还是单图还是无图
            if (materials.size() >= 3) {   //多图
                wmNews.setType(WemediaConstants.WM_NEWS_MANY_IMAGE);
                images = materials.stream().limit(3).collect(Collectors.toList());
            } else if (materials.size() >= 1 && materials.size() < 3) {  //单图
                wmNews.setType(WemediaConstants.WM_NEWS_SINGLE_IMAGE);
                images = materials.stream().limit(1).collect(Collectors.toList());
            } else { //无图
                wmNews.setType(WemediaConstants.WM_NEWS_NONE_IMAGE);
            }
            //修改文章
            if (images != null && images.size() > 0) {
                wmNews.setImages(StringUtils.join(images, ","));
            }
            updateById(wmNews);
        }
        //2.保存封面图片与素材的关系
        if (images != null && images.size() > 0) {
            saveRelativeInfo(images, wmNews.getId(), WemediaConstants.WM_COVER_REFERENCE);
        }
    }

    /**
     * 保存文章内容图片与素材的关系
     *
     * @param materials
     * @param newsId
     */
    private void saveRelativeInfoForContent(List<String> materials, Integer newsId) {
        saveRelativeInfo(materials, newsId, WemediaConstants.WM_CONTENT_REFERENCE);
    }

    /**
     * 保存文章图片与素材的关系到数据库中
     *
     * @param materials
     * @param newsId
     * @param type
     */
    private void saveRelativeInfo(List<String> materials, Integer newsId, Short type) {
        if (materials != null && !materials.isEmpty()) {
            //通过图片的Url查询素材的id
            List<WmMaterial> dbMaterials = materialMapper.selectList(Wrappers.<WmMaterial>lambdaQuery().in(WmMaterial::getUrl, materials));
            //判断素材是否有效
            if (dbMaterials == null || dbMaterials.size() == 0) {
                //手动抛出异常 提示调用者素材失效了，进行数据回滚
                throw new CustomException(AppHttpCodeEnum.MATERIASL_REFERENCE_FAIL);
            }
            if (materials.size() != dbMaterials.size()) {
                throw new CustomException(AppHttpCodeEnum.MATERIASL_REFERENCE_FAIL);
            }
            List<Integer> id = dbMaterials.stream().map(WmMaterial::getId).collect(Collectors.toList());
            //批量保存
            mapper.saveRelations(id, newsId, type);
        }
    }

    /**
     * 提取文章内容中的图片信息
     *
     * @param content
     * @return
     */
    private List<String> ectractUrlInfo(String content) {
        List<String> materials = new ArrayList<>();

        List<Map> maps = JSON.parseArray(content, Map.class);
        for (Map map : maps) {
            if (map.get("type").equals("image")) {
                String imgUrl = (String) map.get("value");
                materials.add(imgUrl);
            }
        }

        return materials;
    }

    /**
     * 保存或修改文章
     */
    private void saveOrUpdateWmNews(WmNews wmNews) {
        wmNews.setUserId(WmThreadLocalUtil.getUser().getId());
        wmNews.setCreatedTime(new Date());
        wmNews.setSubmitedTime(new Date());
        wmNews.setEnable((short) 1); //默认上架
        if (wmNews.getId() == null) {
            //保存操作
            save(wmNews);
        } else {
            //修改操作
            //删除文章图片与素材的关系
            mapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId, wmNews.getId()));
            updateById(wmNews);
        }
    }


}
